package elitech.vietnam.weatherfashion.tabs.settings;

import java.io.IOException;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import elitech.vietnam.weatherfashion.LoginActivity;
import elitech.vietnam.weatherfashion.MainActivity;
import elitech.vietnam.weatherfashion.R;
import elitech.vietnam.weatherfashion.WFApplication;
import elitech.vietnam.weatherfashion.config.Const;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.config.Utils;
import elitech.vietnam.weatherfashion.dialog.ConfirmDialog;
import elitech.vietnam.weatherfashion.dialog.MyProgressDialog;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;
import elitech.vietnam.weatherfashion.tabs.AbstractFragment;
import elitech.vietnam.weatherfashion.ultilities.MyLocation;
import elitech.vietnam.weatherfashion.ultilities.Utilities;
import elitech.vietnam.weatherfashion.ultilities.ValueOption;
import elitech.vietnam.weatherfashion.weatherservice.WeatherObject;
import elitech.vietnam.weatherfashion.weatherservice.WeatherService;
import elitech.vietnam.weatherfashion.widget.NotifyButton;

public class SettingsFragment extends AbstractFragment implements OnClickListener, OnCheckedChangeListener, OnItemSelectedListener {

	public static final String SETTING_RELOAD = "SETTING_RELOAD";
	private boolean isBackFromTurnOnGPS = false;

	public static SettingsFragment THIS;
	/*************************************/
	private Toast toast;
	private ToggleButton toggleButtonViTri;
	private LinearLayout setting01;
	private LinearLayout setting02;
	private LinearLayout setting03;
	private LinearLayout setting04, setting05;
	private LinearLayout setting07;
	private LinearLayout setting08;
	private Button btnLoginLogout;
	private String[] languageCode;
	private TextView mTextLanguage;
	private ValueOption option;
	private NotifyButton button_notification;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.settings, null);
		button_notification = (NotifyButton) view.findViewById(R.id.button_notification);
		
		//button_notification.setOnClickListener(this);

		initView(view);
		THIS = this;
		return view;
	}

	private void initView(View view) {
		// /*************************************/
		option = GlobalValue.getInstance(getActivity()).readOptionInfo();
		// ///// giaDuLieu();
		languageCode = getResources().getStringArray(R.array.languages_code);
		/**************************/
		toggleButtonViTri = (ToggleButton) view.findViewById(R.id.toggleButtonViTri);
		toggleButtonViTri.setChecked(option.isGetLocation());
		toggleButtonViTri.setOnCheckedChangeListener(this);

		/**************************/
		setting01 = (LinearLayout) view.findViewById(R.id.setting01);
		setting01.setOnClickListener(this);

		setting02 = (LinearLayout) view.findViewById(R.id.setting02);
		setting02.setOnClickListener(this);

		setting03 = (LinearLayout) view.findViewById(R.id.setting03);
		setting03.setOnClickListener(this);

		setting04 = (LinearLayout) view.findViewById(R.id.setting04);
		setting04.setOnClickListener(this);
		
		setting05 = (LinearLayout) view.findViewById(R.id.setting05);
		setting05.setOnClickListener(this);

		setting07 = (LinearLayout) view.findViewById(R.id.setting07);
		setting07.setOnClickListener(this);

		setting08 = (LinearLayout) view.findViewById(R.id.setting08);
		setting08.setOnClickListener(this);

		/**************************/
		mTextLanguage = (TextView) view.findViewById(R.id.setting_textLanguage);
		mTextLanguage.setText(getResources().getStringArray(R.array.language)[option.getLanguageIndex()]);
		
		/**************************/
		TextView tvVersion = (TextView) view.findViewById(R.id.tvVersion);
		tvVersion.setText(getAppVersion());

		/***************************/
		btnLoginLogout = (Button) view.findViewById(R.id.btnLoginLogout);
		btnLoginLogout.setOnClickListener(this);

		/****************************/

	}

	@Override
	public void onResume() {
		option = GlobalValue.getInstance(getActivity()).readOptionInfo();
		/*************************************/
		// hide keyboard
		try {
			getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		} catch (Exception e) {}

		super.onResume();
		// login
		((MainActivity) getActivity()).setCurrentNotifyButton(button_notification);

		MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
		if (user == null) {
			btnLoginLogout.setBackgroundResource(R.drawable.button_login1);
			button_notification.setVisibility(View.GONE);
		} else { // logout
			btnLoginLogout.setBackgroundResource(R.drawable.button_logout1);
			button_notification.setVisibility(View.VISIBLE);
		}

		// is come back from TURN ON GPS activity
		if (isBackFromTurnOnGPS) {
			new ReloadWeatherTask().execute();
		}
		isBackFromTurnOnGPS = false;
	}

	private String getAppVersion() {
		String versionName = "1.0";
		try {
			versionName = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName;

		} catch (NameNotFoundException e) {}
		return versionName;
	}

	private void showToast(final String mess, final boolean isCenter) {
		new Handler().post(new Runnable() {
			@Override
			public void run() {
				if (toast != null)
					toast.cancel();
				toast = Toast.makeText(getActivity(), mess, Toast.LENGTH_SHORT);
				if (isCenter)
					toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			}
		});
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
		switch (v.getId()) {
		case R.id.setting01:
			// chua dang nhap
			if (user != null) {
//				getFragmentManager().beginTransaction().replace(R.id.container_framelayout, new EditProfileFragment()).addToBackStack(null).commit();
				((MainActivity) getActivity()).getCurrentBase().replaceFragment(new EditProfileFragment(), true);
			} else {
				intent = new Intent(getActivity(), LoginActivity.class);
				getActivity().startActivityForResult(intent, MainActivity.REQ_CODE_SETTING_CODE);
			}
			break;
		case R.id.setting02:
			// chua dang nhap
			if (user != null) {
//				getFragmentManager().beginTransaction().replace(R.id.container_framelayout, new FriendListChiaLam2Fragment()).addToBackStack(null).commit();
				((MainActivity) getActivity()).getCurrentBase().replaceFragment(new FriendListChiaLam2Fragment(), true);
			} else {
				intent = new Intent(getActivity(), LoginActivity.class);
				getActivity().startActivityForResult(intent, MainActivity.REQ_CODE_SETTING_CODE);
			}

			break;
		case R.id.setting03:
			// Switch duyet thong tin vi tri
			toggleButtonViTri.performClick();
			break;
		case R.id.setting04:
			//toggleButtonThongBao.performClick();
			((MainActivity) getActivity()).getCurrentBase().replaceFragment(new NotificationSettingsFragment(), true);
			break;
		case R.id.setting05:
			((MainActivity) getActivity()).getCurrentBase().replaceFragment(new GuideFragment(), true);
			break;
		case R.id.setting06:
			// Thong tin version - Khong can lam
			break;
		case R.id.setting07:
			// chua dang nhap
			if (user != null) {
//				getFragmentManager().beginTransaction().replace(R.id.container_framelayout, new ChangePasswordFragment()).addToBackStack(null).commit();
				((MainActivity) getActivity()).getCurrentBase().replaceFragment(new ChangePasswordFragment(), true);
			} else {
				intent = new Intent(getActivity(), LoginActivity.class);
				getActivity().startActivityForResult(intent, MainActivity.REQ_CODE_SETTING_CODE);
			}
			break;
		case R.id.setting08:
//			((BaseContainerFragment) getParentFragment()).replaceFragment(new LanguageSettingsFragment(), true);
			((MainActivity) getActivity()).getCurrentBase().replaceFragment(new LanguageSettingsFragment(), true);
			break;
		case R.id.btnLoginLogout:
			// login
			if (user == null) {
				intent = new Intent(getActivity(), LoginActivity.class);
				getActivity().startActivityForResult(intent, MainActivity.REQ_CODE_SETTING_CODE);
			} else { // logout
				new ConfirmDialog.Builder(getActivity())
				.setMessage(getString(R.string.logout_confirm_mess))
				.setYesClick(new ConfirmDialog.OnYesClick() {
					@Override
					public void doClick() {
						new LogoutTask().execute();
					}
				}).build()
				.show();
			}
			break;
		case R.id.button_notification:
			Log.w("Notification", "Num Count: " + WFApplication.getInstance().mListNoti.size());
			((MainActivity) getActivity()).mNotiWindow.showAsDropDown(button_notification);
			((MainActivity) getActivity()).mNotiWindow.notifyDataChanged();
			button_notification.setNumber(0);
			break;
		default:
			break;
		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		int n = requestCode & 0xffff;
		switch (n) {

		case MainActivity.REQ_CODE_SETTING_RELOAD_WEATHER:
			new ReloadWeatherTask().execute();
			break;
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.toggleButtonViTri:

			option.setGetLocation(isChecked);
			GlobalValue.getInstance(getActivity()).writeOptionInfo(option);
			// fileOption.WriteOption(AppConfig.getInstance().valueOption);

			if (isChecked) {
				// Utilities.checkGpsState(getActivity());
				final LocationManager manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

				if (!manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
					Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.weather_gps_disable), Toast.LENGTH_LONG).show();

					try {
						isBackFromTurnOnGPS = true;
						getActivity().startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					showToast(getActivity().getResources().getString(R.string.setting_message_get_location_on), false);

					new ReloadWeatherTask().execute();
				}

			} else {
				showToast(getActivity().getResources().getString(R.string.setting_message_get_location_off), false);

				new ReloadWeatherTask().execute();
			}

			break;
		default:
			break;
		}

	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
		if (option.getLanguageIndex() != position) {
			try {
				String code = languageCode[position];

				// auto
				if (position == 0) {
					code = Utilities.convertCountryCodeToLanguageCode(Const.COUNTRY_CODE);
				}
				option.setLanguageCode(code);
				option.setLanguageIndex(position);
				GlobalValue.getInstance(getActivity()).writeOptionInfo(option);

				restartActivity();
			} catch (Exception e) {
				showToast("Error", true);
			}
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {

	}

	private void restartActivity() {
		Intent intent = getActivity().getIntent();
		intent.putExtra(SETTING_RELOAD, true);
		getActivity().finish();
		startActivity(intent);
	}

	public class ReloadWeatherTask extends AsyncTask<String, Integer, Boolean> {

		public boolean gettingGPS;
		private MyProgressDialog mProgressDialog;
		private WeatherObject weather = null;

		@Override
		protected Boolean doInBackground(String... params) {

			// cho lay GPS xong
			while (gettingGPS) {
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			String myLatitude = GlobalValue.getInstance(getActivity()).readLatitude();
			String myLongtitude = GlobalValue.getInstance(getActivity()).readLongtitude();

			if (myLatitude.equals("") && myLongtitude.equals("") && option.isGetLocation()) {
				publishProgress(0);
			}

			Log.e("GPS-Weather", "Start get weather");
			WeatherService appWService = new WeatherService();
			if ((!myLatitude.equals("") || !myLongtitude.equals("")) && option.isGetLocation()) {

				Log.e("GPS-Weather", "GPS lat " + myLatitude);
				Log.e("GPS-Weather", "GPS lon " + myLongtitude);

				WeatherObject temp = appWService.getWeather(String.valueOf(myLatitude), String.valueOf(myLongtitude));
				if (temp != null && !temp.getListDay().isEmpty()) {
					weather = temp;
				}
			} else {
				Log.e("GPS-Weather", "DEFAULT_CITY" + String.valueOf(Const.DEFAULT_CITY));
				WeatherObject temp = appWService.getWeather(Const.DEFAULT_CITY);
				if (temp != null && !temp.getListDay().isEmpty()) {
					weather = temp;
				}
			}

			Log.e("GPS-Weather", "Stop get weather");
			return true;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			/********************************/
			mProgressDialog = new MyProgressDialog(getActivity());
			mProgressDialog.setCancelable(false);
			mProgressDialog.show();

			/*******************************/

			if (option.isGetLocation()) {
				gettingGPS = true;
				try {
					MyLocation myLocation = new MyLocation();
					Log.e("GPS-Weather", "Start get GPS");
					myLocation.getLocation(getActivity(), new MyLocation.LocationResult() {
						@Override
						public void gotLocation(Location location) {

							if (location != null) {
								String myLatitude = String.valueOf(location.getLatitude());
								String myLongtitude = String.valueOf(location.getLongitude());

								GlobalValue.getInstance(getActivity()).writeLatitude(myLatitude);
								GlobalValue.getInstance(getActivity()).writeLongtitude(myLongtitude);
							}
							Log.e("GPS-Weather", "Stop get GPS " + location);
							gettingGPS = false;
						}
					});
				} catch (Exception e) {
					Utils.Log(e.getMessage());
					gettingGPS = false;
				}
			}
		}

		@Override
		protected void onPostExecute(Boolean result) {
			mProgressDialog.dismiss();
			GlobalValue.getInstance(getActivity()).writeWeatherInfo(weather);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);

			Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.weather_cannot_get_gps), Toast.LENGTH_SHORT).show();
		}

	}

	class LogoutTask extends AsyncTask<Integer, Integer, Boolean> {
		private MyProgressDialog mProgress = new MyProgressDialog(getActivity());
		@Override
		protected void onPreExecute() {
			mProgress.show();
		}
		@Override
		protected Boolean doInBackground(Integer... params) {
			PHPSoapServiceCaller service = new PHPSoapServiceCaller();
			MemberDTO member = GlobalValue.getInstance(getActivity()).readUserInfo();
			try {
				return service.setGCMID(member.getId(), "");
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
		@Override
		protected void onPostExecute(Boolean result) {
			mProgress.dismiss();
			if (!result) {
				Toast.makeText(getActivity(), getString(R.string.cannot_connect_to_server), Toast.LENGTH_SHORT).show();
				return;
			}
			Utils.clearDataLogout(getActivity());
			btnLoginLogout.setBackgroundResource(R.drawable.button_login1);
			button_notification.setVisibility(View.GONE);
			Utilities.stopNotificationService(getActivity());
			// Bo auto login
			option = GlobalValue.getInstance(getActivity()).readOptionInfo();
			option.setPassword("");
			option.setAutoLogin(false);
			GlobalValue.getInstance(getActivity()).writeOptionInfo(option);
		}
	}
}
